package arrray;

import java.util.HashMap;
import java.util.Map;

/**
 * @author huangxianjin
 * @date 2025/8/7 23:38
 * @description "删除有序数组中的重复项-pro"
 */
public class LC_80 {
    //自己的做法-Map统计次数
    public int removeDuplicates(int[] nums) {
        int len = nums.length;
        if (len <= 2) {
            return len;
        }
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            if (map.containsKey(num)) {
                map.put(num, map.get(num) + 1);
            } else {
                map.put(num, 1);
            }
        }
        int index = 0;
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() == 1) {
                nums[index++] = entry.getKey();
            } else {
                nums[index++] = entry.getKey();
                nums[index++] = entry.getKey();
            }
        }
        return index;
    }


    //官方做法-双指针
    public int removeDuplicates2(int[] nums) {
        int n = nums.length;
        if (n <= 2) {
            return n;
        }
        int slow = 2, fast = 2;
        while (fast < n) {
            if (nums[slow - 2] != nums[fast]) {
                nums[slow] = nums[fast];
                ++slow;
            }
            ++fast;
        }
        return slow;
    }
}
